package com.liaoyin.travel.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.business.util.TaskUtil;
import com.liaoyin.travel.dao.BackUserMapper;
import com.liaoyin.travel.dao.task.*;
import com.liaoyin.travel.entity.BackUser;
import com.liaoyin.travel.entity.FileUpload;
import com.liaoyin.travel.entity.UserTeam;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.entity.report.UserBriefing;
import com.liaoyin.travel.entity.task.*;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UserTeamService;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.service.report.UserBriefingService;
import com.liaoyin.travel.util.*;
import com.liaoyin.travel.view.moble.task.TemporaryTaskManageView;
import com.liaoyin.travel.vo.task.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * @项目名：旅投
 * @作者：lijing
 * @描述：任务列表
 * @日期：Created in 2019/7/12 14:55
 */
@Service
@Slf4j
public class TaskService extends BaseService<TaskMapper, Task> {
	
	@Autowired
	private TaskDetailsService taskDetailsService;
	@Autowired
	private UsersService usersService;

	@Resource
	private BackUserMapper backUserMapper;

	@Resource
	private UserTeamService userTeamService;

	@Autowired
	private TaskReceivingRecordsService taskReceivingRecordsService;
	@Autowired
	private TaskExceptionDescriptionService taskExceptionDescriptionService;
	@Autowired
	private TaskLineService taskLineService;
	@Autowired
	private TaskBusinessService taskBusinessService;
	@Autowired
	private UserBriefingService userBriefingService;
	@Autowired
	private TaskTimingService taskTimingService;
	@Resource
	private TaskTimingMapper taskTimingMapper;
	@Autowired
	private TimingTaskParameterService timingTaskParameterService;
	@Autowired
	private TimingTaskDesignatedReceiverService timingTaskDesignatedReceiverService;
	@Resource
	private TimingTaskDesignatedReceiverMapper timingTaskDesignatedReceiverMapper;
	@Resource
	private TaskCompletionRecordMapper taskCompletionRecordMapper;
	@Resource
	private TimingTaskParameterMapper timingTaskParameterMapper;
	@Resource
	private TimingTaskSpecificReleaseTimeMapper taskSpecificReleaseTimeMapper;

	/*****
	 * 
	     * @方法名：selectTaskByIdOnBack
	     * @描述： 根据id查询任务详情-后台
	     * @作者： lijing
	     * @日期： 2019年7月16日
	 */
	public Task selectTaskByIdOnBack(String id) {
		if(id == null) {
			throw new BusinessException("id.is.null");
		}
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("not.login");
		}
		Task task = this.mapper.selectByPrimaryKey(id);
		//查询任务
		List<Task> tasks = this.mapper.selectTaskByUserId(id,null);
		if(tasks == null) {
			throw new BusinessException("task.is.null");
		}
		if (tasks.size() > 1){
			task = tasks.get((int) (Math.random() * tasks.size()));
			String s = this.mapper.selectNickNameByBackUser(task.getUserId());
			if (s != null){
				task.setNickName(s);
			} else {
				String s1 = this.mapper.selectNickNameByUsers(task.getUserId());
				task.setNickName(s1);
			}
		}else{
			task = tasks.get(0);

			String s = this.mapper.selectNickNameByBackUser(task.getUserId());
			if (s != null){
				task.setNickName(s);
			} else {
				String s1 = this.mapper.selectNickNameByUsers(task.getUserId());
				task.setNickName(s1);
			}
		}

		List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(task.getId(), null, null);
		task.setTaskReceivingRecords(taskReceivingRecords);
		Example example = new Example(UserBriefing.class);
		example.and().andEqualTo("taskId",id);
		List<UserBriefing> userBriefings = this.userBriefingService.selectByExample(example);

		task.setUserBriefing(userBriefings.size() > 0  ? 1:0);
		if (userBriefings.size() >0 ){
			task.setUserBriefingTime(userBriefings.get(0).getCreatTime());
		}
		if(task != null) {
			List<TaskDetails> list = this.taskLineService.selectTaskDetailsListByLineId(task.getLineId(), user.getId(),task.getTaskType() == 2 ? 0:1);
			for (TaskDetails details : list) {
				TaskCompletionRecord taskCompletionRecord = new TaskCompletionRecord();
				taskCompletionRecord.setTaskId(task.getId());
				taskCompletionRecord.setTaskDetailsId(details.getId());
				taskCompletionRecord.setTaskFlow(details.getTaskFlow());
				/*if (details.getLat() != null && details.getLog() != null){
					taskCompletionRecord.setLat(details.getLat());
					taskCompletionRecord.setLog(details.getLog());
				}*/
				details.setTaskCompletionRecord((this.taskCompletionRecordMapper.selectOne(taskCompletionRecord)) == null ? null:this.taskCompletionRecordMapper.selectOne(taskCompletionRecord));
			}
			task.setTaskDetailsList(list);
			list=null;
			//查询任务分配
			if(task.getIsSpecify()!=null) {
				String businessId = this.taskBusinessService.selectTaskBusinessId(task.getId());
				//20200429,为了解决部门显示被删除的bug
				task.setIsSpecify((short)1).setBusinessId(businessId);
			}
		}
		System.err.println("task="+task);
		return task;
	}

	/****
	 * 
	     * @方法名：deleteTaskByIdOnBack
	     * @描述： 根据id删除任务-后台
	     * @作者： lijing
	     * @日期： 2019年7月16日
	 */
	@Transactional(rollbackFor = Exception.class)
	public void  deleteTaskByIdOnBack(String ids){
		if(ids == null) {
			throw new BusinessException("id.is.null");
		}
		String[] id = ids.split(",");
		boolean b = true;
		//首先判断是否有用户的此任务在进行中，若有，则无法删除
		if(id !=null &&id.length >0) {
			List<TaskReceivingRecords> list = null;
			for(String s:id) {
				list =this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(s,"","2,4");
				if(list!=null && list.size() >0) {
					b = false;
					list = null;
					break;
				}
			}
		}
		if(b) {
			this.mapper.deleteTaskByIdOnBack(id);
		}else {
			throw new BusinessException("delete.tsak.erreo");
		}
		
	}
	
	
	/*****************************************APP************************************************************/
	
	/****
	 * 
	     * @方法名：selectTaskList
	     * @描述： 查询任务列表--前端
	     * @作者： lijing
	     * @日期： 2019年7月12日
	 */
	public List<Task> selectTaskList(SelectTaskListVo selectTaskListVo){
		System.err.println("selectTaskListVo="+selectTaskListVo);
		if(selectTaskListVo.getQurtyType()==null) {
			throw new BusinessException("qurtyType.is.null");
		}
		//获取当前登录用户的信息
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("not.login");
		}
		/** 景区id */
		String scenicId = user.getScenicId();
		selectTaskListVo.setScenicId(scenicId);
		System.err.println("scenicId="+scenicId);
		//查询结束时间必须比之前多一天
		String endTaskTime = selectTaskListVo.getEndTaskTime();
		if(endTaskTime!=null && endTaskTime.indexOf("-")!=-1){
			String tomorrow = TaskUtil.strGetTomorrow(endTaskTime);
			selectTaskListVo.setEndTaskTime(tomorrow);
		}
		//开始分页插件
		PageHelper.startPage(selectTaskListVo.getNum(),selectTaskListVo.getSize());
		List<Task> list= null;
		/** qurtyType 1：前端员工端查询 */
		if(VariableConstants.STRING_CONSTANT_1.equals(selectTaskListVo.getQurtyType())) {
			//只查询 关于我的，--员工端
			selectTaskListVo.setUserId(user.getId());
			System.err.println("前端员工查任务列表【selectTaskListVo】="+selectTaskListVo);
			list = this.mapper.selectTaskListByEmployee(selectTaskListVo);
			System.out.println("只查关于我的(员工端)----"+list);
			for (Task task : list) {
				if(task.getUserId()!=null){
					BackUser backUser = this.mapper.selectBackUserById(task.getUserId());
					if(backUser!=null && backUser.getId()!=null){
						task.setNickName(backUser.getNickName());
						FileUpload fileUpload = FileUploadUtil.getFileUpload(backUser.getId());
						if(fileUpload!=null){
							task.setHeadPicUrl(fileUpload.getUrl());
						}
					}else{
						Users users = this.mapper.selectUsersById(task.getUserId());
						System.err.println("task.getUserId()"+task.getUserId());
						System.err.println("users="+users);
						if(users==null){
							System.err.println("没有查到用户");
						}else{
							task.setNickName(users.getNickName());
							FileUpload fileUpload = FileUploadUtil.getFileUpload(users.getHeadPicId());
							if(fileUpload!=null){
								task.setHeadPicUrl(fileUpload.getUrl());
							}
						}
					}
				}
			}
		}else if(VariableConstants.STRING_CONSTANT_2.equals(selectTaskListVo.getQurtyType())) {
			//qurtyType 2：前端管理端  3：后台查询
			/**
			 * 更改成时间范围内的搜索,所以这个搜索条件取消
			 */
			/*if(selectTaskListVo.getTaskTime()==null) {
				//如果时间为空，默认今天
				selectTaskListVo.setTaskTime(DateUtil.formatyyyyMMddHHmmss(new Date()));
			}*/
			//管理端
			if(user.getUserType()==null || !VariableConstants.STRING_CONSTANT_2.equals(user.getUserType())) {
				throw new BusinessException("auth.is.error");
			}
			//判断当前用户是否是部门经理
			if(user.getAssumeOffice()==null || !VariableConstants.STRING_CONSTANT_1.equals(user.getAssumeOffice().toString())) {
				throw new BusinessException("auth.is.error");
			}
			if(VariableConstants.STRING_CONSTANT_1.equals(selectTaskListVo.getTaskQurty())) {
				//查询自己及下属的所有任务
				List<UserTeam> userteamList = user.getUserTeamList();
				if(userteamList==null || userteamList.size() == 0) {
		        	throw new BusinessException("team.is.null");
		        }
		        StringBuffer teamId = new StringBuffer();
		        for(UserTeam u:userteamList) {
		        	teamId.append(u.getTeamId()+",");
		        }

				selectTaskListVo.setTeamId(teamId.toString());
				System.err.println("部门领导查询【selectTaskListVo】="+selectTaskListVo);
				list= this.mapper.selectTaskListByManagement(selectTaskListVo);
				/*list.forEach(task -> {
					System.err.println(task);
				});*/
			}else if(VariableConstants.STRING_CONSTANT_2.equals(selectTaskListVo.getTaskQurty())) {
				//只查询 关于我的任务
				selectTaskListVo.setUserId(user.getId());
				list = this.mapper.selectTaskListByEmployee(selectTaskListVo);
			}else if(VariableConstants.STRING_CONSTANT_3.equals(selectTaskListVo.getTaskQurty())) {
				//查询我发布的任务
				selectTaskListVo.setUserId(user.getId());
				System.err.println("----查询我发布的任务---selectTaskListVo.getId()="+selectTaskListVo.getId());
				list = this.mapper.selectTaskListOnBack(selectTaskListVo);
			}
//			System.err.println(selectTaskListVo);
//			System.err.println("list="+list);
			if(list!=null && !list.isEmpty()){
				for (Task task : list) {
					String receiverId = task.getReceiverId();
					System.err.println("receiverId="+receiverId);
					String taskId = task.getId();
					//统计任务领取人数量
					int taskReceiverCount = this.taskReceivingRecordsService.countTaskReceivingRecordsByTaskId(taskId);
					if(receiverId != null){
						Users users = this.mapper.selectUsersById(receiverId);
						if(users!=null && users.getNickName()!=null){
							String nickName = users.getNickName();
							if(taskReceiverCount>1){
								nickName = nickName+"等"+taskReceiverCount+"人";
							}
							task.setReceiver(nickName);
						}
					}
					if(task.getUserId()!=null){
						BackUser backUser = this.mapper.selectBackUserById(task.getUserId());
						if(backUser!=null && backUser.getId()!=null){
							task.setNickName(backUser.getNickName());
							FileUpload fileUpload = FileUploadUtil.getFileUpload(backUser.getId());
							if(fileUpload!=null){
								task.setHeadPicUrl(fileUpload.getUrl());
							}
						}else{
							Users users = this.mapper.selectUsersById(task.getUserId());
							System.err.println("task.getUserId()"+task.getUserId());
							System.err.println("users="+users);
							if(users==null){
								System.err.println("没有查到用户");
							}else{
								task.setNickName(users.getNickName());
								FileUpload fileUpload = FileUploadUtil.getFileUpload(users.getHeadPicId());
								if(fileUpload!=null){
									task.setHeadPicUrl(fileUpload.getUrl());
								}
							}
						}
					}


				}
			}

		}else if(VariableConstants.STRING_CONSTANT_3.equals(selectTaskListVo.getQurtyType())) {
			//后台
			list = this.mapper.selectTaskListOnBack(selectTaskListVo);
			for (Task task : list) {
				String receiverId = task.getReceiverId();
				String taskId = task.getId();
				int taskReceiverCount = this.taskReceivingRecordsService.countTaskReceivingRecordsByTaskId(taskId);
				if(receiverId != null){
					Users users = this.mapper.selectUsersById(receiverId);
					System.err.println("321user="+users);
					if(users!=null && users.getNickName()!=null){
						String nickName = users.getNickName();
						if(taskReceiverCount>1){
							nickName = nickName+"等"+taskReceiverCount+"人";
						}
						task.setReceiver(nickName);
						System.err.println("领取人姓名="+task.getReceiver());
					}

				}
				if(task.getUserId()!=null){
					BackUser backUser = this.mapper.selectBackUserById(task.getUserId());
					if(backUser!=null && backUser.getId()!=null){
						task.setNickName(backUser.getNickName());
						FileUpload fileUpload = FileUploadUtil.getFileUpload(backUser.getId());
						if(fileUpload!=null){
							task.setHeadPicUrl(fileUpload.getUrl());
						}
					}else{
						Users users = this.mapper.selectUsersById(task.getUserId());
						System.err.println("task.getUserId()"+task.getUserId());
						System.err.println("users="+users);
						if(users==null){
							System.err.println("没有查到用户");
						}else{
							task.setNickName(users.getNickName());
							FileUpload fileUpload = FileUploadUtil.getFileUpload(users.getHeadPicId());
							if(fileUpload!=null){
								task.setHeadPicUrl(fileUpload.getUrl());
							}
						}

					}
				}
			}
		}else {
			throw new BusinessException("type.is.null");
		}
//		System.out.println(list.toString());
		System.err.println("==========2==========selectTaskListVo.getNum()="+selectTaskListVo.getNum());
		PageInfo<Task> p = new PageInfo<>(list);
		//因为这个方法离职的同事没有返回分页对象，所以我只能手写来抛出异常,阻止没有数据了还继续调用接口
		if(TaskUtil.isNotThereAnyData(selectTaskListVo.getNum(),p)){
			System.err.println("selectTaskListVo.getNum()="+selectTaskListVo.getNum());
			System.err.println("p="+p);
//			throw new BusinessException("isTheLastPage");
			return new ArrayList<>();
		}
		System.err.println(p);
		return p.getList();
	}

	/****
	 * 
	     * @方法名：selectTaskByIdOnMoble
	     * @描述： 根据id查询任务详情-前端
	     * @作者： lijing
	     * @日期： 2019年7月15日
	 */
	public Task selectTaskByIdOnMoble(String id) {
		if(id == null) {
			throw new BusinessException("id.is.null");
		}
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("not.login");
		}
		System.err.println("user.getId()="+user.getId());
		//查询任务 9d64205504f1420d844633bbfedb5c82
		List<Task> tasks = this.mapper.selectTaskByUserId(id, user.getId());
		if(tasks==null || tasks.size() ==0) {
			throw new BusinessException("task.is.null");
		}
		Task task = tasks.get(0);

		/** 赋值 任务发布人类型 */
		//任务发布人id
		String userId = task.getUserId();
		Users publisher = this.usersService.selectUsersById(userId);
		if(publisher!=null){
			task.setPublisherType(VariableConstants.STRING_CONSTANT_1);
		}else{
			BackUser backUser = this.backUserMapper.selectBackUserById(userId);
			if(backUser!=null){
				task.setPublisherType(VariableConstants.STRING_CONSTANT_2);
			}
		}

		String s = this.mapper.selectNickNameByBackUser(task.getUserId());
		List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(task.getId(), user.getId(), null);
		task.setTaskReceivingRecords(taskReceivingRecords);
		List<UserBriefing> briefing = this.userBriefingService.getUserBriefingByTaskIdAndUserId(id, user.getId());
		task.setUserBriefing(briefing.size() > 0 ? 0:1);
		if (null != briefing && briefing.size() > 0){
			task.setUserBriefingTime(briefing.get(0).getCreatTime());
		}
		if (s != null){
			task.setNickName(s);
		} else {
			String s1 = this.mapper.selectNickNameByUsers(task.getUserId());
			task.setNickName(s1);
		}
		if(task != null) {
			List<TaskDetails> list = this.taskLineService.selectTaskDetailsListByLineId(task.getLineId(), user.getId(),task.getTaskType() == 2 ? 0:1);
			for (TaskDetails details : list) {
				TaskCompletionRecord taskCompletionRecord = new TaskCompletionRecord();
				taskCompletionRecord.setTaskId(task.getId());
				taskCompletionRecord.setTaskDetailsId(details.getId());
				taskCompletionRecord.setTaskFlow(details.getTaskFlow());
				details.setTaskCompletionRecord((this.taskCompletionRecordMapper.selectOne(taskCompletionRecord)) == null ? null:this.taskCompletionRecordMapper.selectOne(taskCompletionRecord));
			}
			task.setTaskDetailsList(list);

			//查询任务分配
			/*if(task.getIsSpecify()!=null) {
				String businessId = this.taskBusinessService.selectTaskBusinessId(task.getId());
				task.setBusinessId(businessId);
			}*/
		}


		System.err.println("task="+task);
		return task;
	}
	
	
	
	/******
	 * 
	     * @方法名：insertTask
	     * @描述： 发布任务
	     * @作者： lijing
	     * @日期： 2019年7月15日
	 */
	/*@Transactional(rollbackFor=BusinessException.class)
	public void insertTask(InsertTaskVo insertTaskVo) {
		//获取用户登录信息
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("not.login");
		}
		//任务实体
		Task task = insertTaskVo.getTask();
        System.err.println("1.task.getUserId()"+task.getUserId());
        System.err.println("1.user.getId()"+user.getId());
		//任务名称为空
		if (task.getTaskName() == null || "".equals(task.getTaskName())){
			//不懂这个是什么逻辑？？？
			task.setTaskName(task.getTaskTypeDisplay()+new Date());
		}
		if(task == null) {
			throw new BusinessException("task.is.null","任务为空，发布失败");
		}
		if(insertTaskVo.getBusinessId() ==null) {
			throw new BusinessException("businessId.is.null","任务指定为空");
		}
		if(task.getTaskType()==null) {
			throw new BusinessException("taskType.is.null","任务类型为空");
		}
		//如果是巡更任务，线路id不能为空
		if(task.getTaskType() !=null && task.getTaskType().intValue()==3) {
			if(task.getLineId()==null) {
				throw new BusinessException("line.is.null","线路为空");
			}
		}
		else {
			if(insertTaskVo.getTaskLineVo()==null){
				throw new BusinessException("line.is.null","线路为空");
			}
			TaskLine tl = new TaskLine();
			tl.setLineName(insertTaskVo.getTaskLineVo().getLineName());
			task.setLineId(this.taskLineService.insertOrUpdateTaskLine(tl));
			tl = null;
		}
		// ???用管理员查询自己领取过的任务？？？我感觉这个写的逻辑不对
		List<Task> list = selectTaskUserList(user.getId(), "2");
		if(list !=null && list.size() >0) {
			for(Task t:list) {
				//如果是紧急任务
				if(t.getTaskLevel() !=null && t.getTaskLevel().intValue()==2) {
					throw new BusinessException("taskLevel.is.two");
				}
			}
		}
		//主键
		String id = UUIDUtil.getUUID();
		task.setId(id);
		//创建时间
		task.setCreatTime(new Date());
		//默认未删除
		task.setIsDelete((short)0);
		//任务发布人
		if(task.getUserId()==null){
			task.setUserId(user.getId());
		}
		//是否指定所有人
		String isSpecify = String.valueOf(task.getIsSpecify());
		if ("1".equals(isSpecify)){
			Example example = new Example(TaskReceivingRecords.class);
			example.and().andEqualTo("userId",insertTaskVo.getBusinessId().split(",")[0]).andEqualTo("tastStatus",2);
			List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectByExample(example);
			for (TaskReceivingRecords receivingRecord : taskReceivingRecords) {
				String taskId = receivingRecord.getTaskId();
				Task task1 = this.mapper.selectByPrimaryKey(taskId);
				if ( task1.getTaskLevel() == 2 ){
//					throw new BusinessException("user.is.Busy");
				} else if (receivingRecord.getTastStatus() == 2 && task1.getTaskLevel() == 1 && task.getTaskLevel() == 2){
					tempTaskMap.put(id, receivingRecord.getId());
					receivingRecord.setTastStatus((short)4);
					taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
				}
			}
            System.err.println("2.指定人员--");
            System.err.println("2.task.userId="+task.getUserId());
		}else if ("2".equals(isSpecify)){
			//部门
			List<Users> users = this.usersService.selectUsersListOnTeamById(insertTaskVo.getBusinessId());
			for (Users u : users) {
				Example example = new Example(TaskReceivingRecords.class);
				example.and().andEqualTo("userId",u.getId()).andEqualTo("tastStatus",2);
				List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectByExample(example);
				for (TaskReceivingRecords receivingRecord : taskReceivingRecords) {
					String taskId = receivingRecord.getTaskId();
					Task task1 = this.mapper.selectByPrimaryKey(taskId);
					if (task1.getTaskLevel() == 2 ){
//						throw new BusinessException("user.is.Busy");
					}else if (receivingRecord.getTastStatus() == 2 && task1.getTaskLevel() == 1 && task.getTaskLevel() == 2){
						tempTaskMap.put(id, receivingRecord.getId());
						receivingRecord.setTastStatus((short)4);
						taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
					}
				}
			}
            System.err.println("3.指定部门--");
            System.err.println("3.task.userId="+task.getUserId());
		}else if ("3".equals(isSpecify)){
			//工种
			Example exp = new Example(Users.class);
			exp.and().andEqualTo("workId",insertTaskVo.getBusinessId());
			List<Users> users = this.usersService.selectByExample(exp);
			for (Users u : users) {
				Example example = new Example(TaskReceivingRecords.class);
				example.and().andEqualTo("userId",u.getId()).andEqualTo("tastStatus",2);
				List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectByExample(example);
				for (TaskReceivingRecords receivingRecord : taskReceivingRecords) {
					String taskId = receivingRecord.getTaskId();
					Task task1 = this.mapper.selectByPrimaryKey(taskId);
					if (task1.getTaskLevel() == 2){
//						throw new BusinessException("user.is.Busy");
					}else if (receivingRecord.getTastStatus() == 2 && task1.getTaskLevel() == 1 && task.getTaskLevel() == 2){
						tempTaskMap.put(id, receivingRecord.getId());
						receivingRecord.setTastStatus((short)4);
						taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
					}
				}
			}
            System.err.println("4.指定工种--");
            System.err.println("4.task.userId="+task.getUserId());
		}
		if (task.getTaskType() == 2){
			TaskLine taskLine = new TaskLine();
			List<TaskDetails> detailsList = new ArrayList<>();
			TaskDetails details = new TaskDetails();
			details.setId(UUIDUtil.getUUID());
			details.setIsDelete((short)0);
			details.setTaskId(task.getId());
			details.setTaskFlow((short)1);
			details.setTaskOperation((short)1);
			details.setLat(task.getTaskLat());
			details.setLog(task.getTaskLog());
			detailsList.add(details);
			System.out.println(detailsList.toString());
			taskLine.setTaskDetailsList(detailsList);
			String s = taskLineService.insertOrUpdateTaskLine(taskLine);
			task.setLineId(s);
		}
		int k = this.mapper.insertSelective(task);
		boolean flag = true;
		if(k >0) {
			//添加任务指定的领取人
			if(task.getIsSpecify() !=null) {
				this.taskBusinessService.insertTaskBusiness(String.valueOf(task.getIsSpecify()), insertTaskVo.getBusinessId(), id);
			}
		}
        System.err.println("指定添加领取人之后--");
        System.err.println("task.userId="+task.getUserId());
		HashMap<String, String> map = new HashMap<>();
		map.put("fromUserId",PartyUtil.getCurrentUserInfo().getId());
		if(VariableConstants.STRING_CONSTANT_1.equals(isSpecify)){
			System.out.println("1111111::::::"+insertTaskVo.getBusinessId());
			String[] split = insertTaskVo.getBusinessId().split(",");
			StringBuffer stringBuffer = new StringBuffer();
			for (String s : split) {
				stringBuffer.append(s + "&");
			}
			//仅对指定员工发生任务信息
			map.put("toUserId",stringBuffer.toString());
		} else if (VariableConstants.STRING_CONSTANT_2.equals(isSpecify)){
			System.out.println("22222222");
			//仅对该部门的人发送任务信息
			String[] Bid = insertTaskVo.getBusinessId().split(",");
			List<Users> users = this.usersService.selectselectUsersListBybusinessIds("1", Bid);
			StringBuffer ids = new StringBuffer();
			for (Users u : users) {
				ids.append(u.getId() + "&");
			}
			map.put("toUserId",ids.toString());
			map.put("objectName","RC:TxtMsg");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("content", "您有新的任务！");
			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
			map.put("content",jsonObject.toJSONString());
			map.put("pushContent","您有新的任务");
			try {
				String s = RongUtils.groupManagement(map, "7");
				System.out.println(s);
			} catch (Exception e) {
				e.printStackTrace();
			}
			flag = false;

		} else if (VariableConstants.STRING_CONSTANT_3.equals(isSpecify)){
			System.out.println("33333333");
			//仅对该工种发送任务信息
			String[] Bid = insertTaskVo.getBusinessId().split(",");
			List<Users> users = this.usersService.selectselectUsersListBybusinessIds("2", Bid);
			StringBuffer ids = new StringBuffer();
			for (Users u : users) {
				ids.append(u.getId() + "&");
			}
			map.put("toUserId",ids.toString());
			map.put("objectName","RC:TxtMsg");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("content", "您有新的任务！");
			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
			map.put("content",jsonObject.toJSONString());
			map.put("pushContent","您有新的任务");
			try {
				String s = RongUtils.groupManagement(map, "7");
				System.out.println(s);
			} catch (Exception e) {
				e.printStackTrace();
			}
			flag = false;
		}
		if(flag){
			map.put("objectName","RC:TxtMsg");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("content", "您有新的任务！");
			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
			map.put("content",jsonObject.toJSONString());
			map.put("pushContent","您有新的任务");
			try {
				String s = RongUtils.groupManagement(map, "7");
				System.out.println(s);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
        System.err.println("5.程序执行到最后--");
        System.err.println("5.task.userId="+task.getUserId());
	}*/

	/******
	 *
	 * @方法名：insertTask
	 * @描述： 发布任务(有多少个人就新增了多少条任务)
	 * @作者： lijing
	 * @日期： 2019年7月15日
	 */
	//@Transactional(rollbackFor=BusinessException.class)
	public void insertTask(InsertTaskVo insertTaskVo) {
		//获取用户登录信息
		UserInfo currentUser = PartyUtil.getCurrentUserInfo();
		Optional.ofNullable(currentUser).orElseThrow(() -> new BusinessException("not.login"));
		/** 景区id */
		String scenicId = currentUser.getScenicId();

		//任务实体
		Task task = insertTaskVo.getTask();

		//任务名称为空
		if (task.getTaskName() == null || "".equals(task.getTaskName())){
			//不懂这个是什么逻辑？？？
			task.setTaskName(task.getTaskTypeDisplay()+new Date());
		}
		if(task == null) {
			throw new BusinessException("task.is.null","任务为空，发布失败");
		}
		if(insertTaskVo.getBusinessId() ==null) {
			throw new BusinessException("businessId.is.null","任务指定为空");
		}
		if(task.getTaskType()==null) {
			throw new BusinessException("taskType.is.null","任务类型为空");
		}
		//如果是巡更任务，线路id不能为空
		if(task.getTaskType() !=null && task.getTaskType().intValue()==3) {
			if(task.getLineId()==null) {
				throw new BusinessException("line.is.null","线路为空");
			}
		}
		/** ???用管理员查询自己领取过的任务？？？我感觉这个写的逻辑不对*/
		/*List<Task> list = selectTaskUserList(currentUser.getId(), "2");
		if(list !=null && list.size() >0) {
			for(Task t:list) {
				//如果是紧急任务
				if(t.getTaskLevel() !=null && t.getTaskLevel().intValue()==2) {
					throw new BusinessException("taskLevel.is.two");
				}
			}
		}*/


		/** 是否指定所有人*/
		String isSpecify = String.valueOf(task.getIsSpecify());


		//完善要新增的任务实体
		//创建时间
		task.setCreatTime(new Date());
		//默认未删除
		task.setIsDelete((short)0);
		//任务发布人
		if(task.getUserId()==null){
			task.setUserId(currentUser.getId());
		}

		//** 更改以前的逻辑，有多少个领取人，就新增多少条任务

		String businessIds = insertTaskVo.getBusinessId();
		//通过是否指定人员和businessId获取到用户id列表
		List<String> userIdList = this.taskBusinessService.selectUserIdByBusinessIds(isSpecify,businessIds);
		List<Task> taskList = new ArrayList<>();
		for(int i = 0;i<userIdList.size();i++){
			Task task1 = new Task();
			BeanUtils.copyProperties(task,task1);
			task1.setId(UUIDUtil.getUUID()).setScenicId(scenicId);
			System.err.println("781-task.getId()="+task1.getId());
			taskList.add(task1);
		}
		//组装新增指定领取人的参数
		List<TaskIdAndUserIdVo> taskIdAndUserIdVoList = new ArrayList<>();
		/*taskList.forEach(task1 -> {
			System.err.println("task1.getId()="+task1.getId());
		});*/
		String taskManagerId = SnowIdUtil.getInstance().nextId();
		//新增taskId
		taskList.forEach(task1 -> {
			//如果是线路任务
			if (task1.getTaskType() == 2){
				TaskLine taskLine = new TaskLine();
				List<TaskDetails> detailsList = new ArrayList<>();
				TaskDetails details = new TaskDetails();
				details.setId(UUIDUtil.getUUID());
				details.setIsDelete((short)0);
				details.setTaskId(task1.getId());
				details.setTaskFlow((short)1);
				details.setTaskOperation((short)1);
				details.setLat(task1.getTaskLat());
				details.setLog(task1.getTaskLog());
				//景区id
				details.setScenicId(scenicId);
				detailsList.add(details);

				taskLine.setTaskDetailsList(detailsList);
				String s = taskLineService.insertOrUpdateTaskLine(taskLine);
				task1.setLineId(s);
			}
			//发布方式:临时发布
			task1.setReleaseWay(VariableConstants.STRING_CONSTANT_2);
			//临时任务要有用于查询任务管理的管理参数
			task1.setTaskManagerId(taskManagerId);
			//新增任务
			System.err.println("taskId："+task1.getId());
			this.mapper.insertSelective(task1);
			TaskIdAndUserIdVo taskIdAndUserIdVo = new TaskIdAndUserIdVo()
					.setTaskId(task1.getId())
					.setTaskMangerId(taskManagerId)
					.setReleaseWay(VariableConstants.STRING_CONSTANT_2);
			taskIdAndUserIdVoList.add(taskIdAndUserIdVo);
		});
		//新增userId
		for(int i = 0;i<userIdList.size();i++){
			taskIdAndUserIdVoList.get(i).setUserId(userIdList.get(i));
		}
		//新增指定任务领取人
		this.taskBusinessService.insertTaskBusinessByUserIdsAndTaskIds(taskIdAndUserIdVoList,isSpecify);

		boolean flag = true;

		System.err.println("指定添加领取人之后--");
		System.err.println("task.userId="+task.getUserId());
		HashMap<String, String> map = new HashMap<>();

		//考虑到景区管理员没有注册融云，景区管理员发消息直接用昵称显示
		String fromUserId = currentUser.getId();
		if(currentUser.getAccountType()!=null){
			fromUserId = currentUser.getNickName()+"(后台管理员)";
		}
		map.put("fromUserId",fromUserId);
		if(VariableConstants.STRING_CONSTANT_1.equals(isSpecify)){
			System.err.println("1111111::::::"+insertTaskVo.getBusinessId());
			String[] split = insertTaskVo.getBusinessId().split(",");
			StringBuffer stringBuffer = new StringBuffer();
			for (String s : split) {
				stringBuffer.append(s + "&");
			}
			//仅对指定员工发生任务信息
			map.put("toUserId",stringBuffer.toString());
		} else if (VariableConstants.STRING_CONSTANT_2.equals(isSpecify)){
			System.err.println("22222222");
			//仅对该部门的人发送任务信息
			String[] Bid = insertTaskVo.getBusinessId().split(",");
			List<Users> users = this.usersService.selectselectUsersListBybusinessIds("1", Bid);
			StringBuffer ids = new StringBuffer();
			for (Users u : users) {
				ids.append(u.getId() + "&");
			}
			map.put("toUserId",ids.toString());
			map.put("objectName","RC:TxtMsg");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("content", "您有新的任务！");
			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
			map.put("content",jsonObject.toJSONString());
			map.put("pushContent","您有新的任务");
			try {
				String s = RongUtils.groupManagement(map, "7");
				System.err.println(s);
			} catch (Exception e) {
				e.printStackTrace();
			}
			flag = false;

		} else if (VariableConstants.STRING_CONSTANT_3.equals(isSpecify)){
			System.out.println("33333333");
			//仅对该工种发送任务信息
			String[] Bid = insertTaskVo.getBusinessId().split(",");
			List<Users> users = this.usersService.selectselectUsersListBybusinessIds("2", Bid);
			StringBuffer ids = new StringBuffer();
			for (Users u : users) {
				ids.append(u.getId() + "&");
			}
			map.put("toUserId",ids.toString());
			map.put("objectName","RC:TxtMsg");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("content", "您有新的任务！");
			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
			map.put("content",jsonObject.toJSONString());
			map.put("pushContent","您有新的任务");
			try {
				String s = RongUtils.groupManagement(map, "7");
				System.err.println(s);
			} catch (Exception e) {
				e.printStackTrace();
			}
			flag = false;
		}
		if(flag){
			map.put("objectName","RC:TxtMsg");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("content", "您有新的任务！");
			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
			map.put("content",jsonObject.toJSONString());
			map.put("pushContent","您有新的任务");
			try {
				String s = RongUtils.groupManagement(map, "7");
				System.err.println(s);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.err.println("5.程序执行到最后--");
		System.err.println("5.task.userId="+task.getUserId());
	}

	/**
	 * @方法名：insertTaskTime
	 * @描述： 发布定时任务(有多少个人发多少条)
	 * @作者： kuang.jiazhuo
	 * @日期： Created in 2019/12/3 21:12
	 */
	@Transactional(rollbackFor = Exception.class)
	public void insertTaskTime(InsertTaskVo insertTaskVo) {

		//任务实体
		Task task = insertTaskVo.getTask();
		//单位id
		String scenicId = task.getScenicId();

		System.err.println("1.task.getUserId()"+task.getUserId());
		//任务名称为空
		if (task.getTaskName() == null || "".equals(task.getTaskName())){
			//不懂这个是什么逻辑？？？
			task.setTaskName(task.getTaskTypeDisplay()+new Date());
		}
		if(task == null) {
			throw new BusinessException("task.is.null","任务为空，发布失败");
		}
		if(insertTaskVo.getBusinessId() ==null) {
			throw new BusinessException("businessId.is.null","任务指定为空");
		}
		if(task.getTaskType()==null) {
			throw new BusinessException("taskType.is.null","任务类型为空");
		}
		//如果是巡更任务，线路id不能为空
		if(task.getTaskType() !=null && task.getTaskType().intValue()==3) {
			if(task.getLineId()==null) {
				throw new BusinessException("line.is.null","线路为空");
			}
		}
		/** ???用管理员查询自己领取过的任务？？？我感觉这个写的逻辑不对 */
		/*List<Task> list = selectTaskUserList(task.getUserId(), "2");
		if(list !=null && list.size() >0) {
			for(Task t:list) {
				//如果是紧急任务
				if(t.getTaskLevel() !=null && t.getTaskLevel().intValue()==2) {
					throw new BusinessException("taskLevel.is.two");
				}
			}
		}*/


		//是否指定所有人
		String isSpecify = String.valueOf(task.getIsSpecify());


		/** 完善要新增的任务实体*/
		//创建时间
		task.setCreatTime(new Date());
		//默认未删除
		task.setIsDelete((short)0);

		/** 更改以前的逻辑，有多少个领取人，就新增多少条任务*/

		String businessIds = insertTaskVo.getBusinessId();
		//通过是否指定人员和businessId获取到用户id列表
		List<String> userIdList = this.taskBusinessService.selectUserIdByBusinessIds(isSpecify,businessIds);
		userIdList.forEach(userId->{
			System.err.println("900-userId："+userId);
		});
		List<Task> taskList = new ArrayList<>();
		for(int i = 0;i<userIdList.size();i++){
			Task task1 = new Task();
			BeanUtils.copyProperties(task,task1);
			task1.setId(UUIDUtil.getUUID());
			System.err.println("724-task.getId()="+task1.getId());
			taskList.add(task1);
		}
		//组装新增指定领取人的参数
		List<TaskIdAndUserIdVo> taskIdAndUserIdVoList = new ArrayList<>();
		/*taskList.forEach(task1 -> {
			System.err.println("task1.getId()="+task1.getId());
		});*/
		//新增taskId
		taskList.forEach(task1 -> {
			//如果是线路任务
			if (task1.getTaskType() == 2){
				TaskLine taskLine = new TaskLine();
				List<TaskDetails> detailsList = new ArrayList<>();
				TaskDetails details = new TaskDetails();
				details.setId(UUIDUtil.getUUID());
				details.setIsDelete((short)0);
				details.setTaskId(task1.getId());
				details.setTaskFlow((short)1);
				details.setTaskOperation((short)1);
				details.setLat(task1.getTaskLat());
				details.setLog(task1.getTaskLog());
				details.setScenicId(scenicId);
				detailsList.add(details);
				System.out.println(detailsList.toString());
				taskLine.setTaskDetailsList(detailsList);
				String s = taskLineService.insertTimingTaskLine(taskLine);
				task1.setLineId(s);
			}
			//发布方式:定时发布
			task1.setReleaseWay(VariableConstants.STRING_CONSTANT_1);

			//新增任务
			System.err.println("taskId："+task1.getId());
			this.mapper.insertSelective(task1);
			TaskIdAndUserIdVo taskIdAndUserIdVo = new TaskIdAndUserIdVo()
					.setTaskId(task1.getId())
					.setReleaseWay(VariableConstants.STRING_CONSTANT_1)
					.setScenicId(scenicId);
			taskIdAndUserIdVoList.add(taskIdAndUserIdVo);
		});

		//新增userId
		for(int i = 0;i<userIdList.size();i++){
			taskIdAndUserIdVoList.get(i).setUserId(userIdList.get(i));
		}
		//新增指定任务领取人
		this.taskBusinessService.insertTaskBusinessByUserIdsAndTaskIds(taskIdAndUserIdVoList,isSpecify);

		boolean flag = true;

		System.err.println("指定添加领取人之后--");
		System.err.println("task.userId="+task.getUserId());
		HashMap<String, String> map = new HashMap<>();

		//考虑到景区管理员没有注册融云，景区管理员发消息直接用昵称显示
		String fromUserId = this.usersService.selectFromUserIdByUserId(task.getUserId());
		map.put("fromUserId",fromUserId);
		if(VariableConstants.STRING_CONSTANT_1.equals(isSpecify)){
			System.out.println("1111111::::::"+insertTaskVo.getBusinessId());
			String[] split = insertTaskVo.getBusinessId().split(",");
			StringBuffer stringBuffer = new StringBuffer();
			for (String s : split) {
				stringBuffer.append(s + "&");
			}
			//仅对指定员工发生任务信息
			map.put("toUserId",stringBuffer.toString());
		} else if (VariableConstants.STRING_CONSTANT_2.equals(isSpecify)){
			System.out.println("22222222");
			//仅对该部门的人发送任务信息
			String[] Bid = insertTaskVo.getBusinessId().split(",");
			List<Users> users = this.usersService.selectselectUsersListBybusinessIds("1", Bid);
			StringBuffer ids = new StringBuffer();
			for (Users u : users) {
				ids.append(u.getId() + "&");
			}
			map.put("toUserId",ids.toString());
			map.put("objectName","RC:TxtMsg");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("content", "您有新的任务！");
			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
			map.put("content",jsonObject.toJSONString());
			map.put("pushContent","您有新的任务");
			try {
				String s = RongUtils.groupManagement(map, "7");
				System.out.println(s);
			} catch (Exception e) {
				e.printStackTrace();
			}
			flag = false;

		} else if (VariableConstants.STRING_CONSTANT_3.equals(isSpecify)){
			System.out.println("33333333");
			//仅对该工种发送任务信息
			String[] Bid = insertTaskVo.getBusinessId().split(",");
			List<Users> users = this.usersService.selectselectUsersListBybusinessIds("2", Bid);
			StringBuffer ids = new StringBuffer();
			for (Users u : users) {
				ids.append(u.getId() + "&");
			}
			map.put("toUserId",ids.toString());
			map.put("objectName","RC:TxtMsg");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("content", "您有新的任务！");
			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
			map.put("content",jsonObject.toJSONString());
			map.put("pushContent","您有新的任务");
			try {
				String s = RongUtils.groupManagement(map, "7");
				System.out.println(s);
			} catch (Exception e) {
				e.printStackTrace();
			}
			flag = false;
		}
		if(flag){
			map.put("objectName","RC:TxtMsg");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("content", "您有新的任务！");
			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
			map.put("content",jsonObject.toJSONString());
			map.put("pushContent","您有新的任务");
			try {
				String s = RongUtils.groupManagement(map, "7");
				System.out.println(s);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.err.println("5.程序执行到最后--");
		System.err.println("5.task.userId="+task.getUserId());
	}

	/**
	 * @方法名：insertTaskTime
	 * @描述： 发布定时任务(多个人只发一条)
	 * @作者： kuang.jiazhuo
	 * @日期： Created in 2019/12/3 21:12
	 */
//	@Transactional(rollbackFor = Exception.class)
//	public void insertTaskTime(InsertTaskVo insertTaskVo) {
//
//		//任务实体
//		Task task = insertTaskVo.getTask();
//		System.err.println("1.task.getUserId()"+task.getUserId());
//		//任务名称为空
//		if (task.getTaskName() == null || "".equals(task.getTaskName())){
//			//不懂这个是什么逻辑？？？
//			task.setTaskName(task.getTaskTypeDisplay()+new Date());
//		}
//		if(task == null) {
//			throw new BusinessException("task.is.null","任务为空，发布失败");
//		}
//		if(insertTaskVo.getBusinessId() ==null) {
//			throw new BusinessException("businessId.is.null","任务指定为空");
//		}
//		if(task.getTaskType()==null) {
//			throw new BusinessException("taskType.is.null","任务类型为空");
//		}
//		//如果是巡更任务，线路id不能为空
//		if(task.getTaskType() !=null && task.getTaskType().intValue()==3) {
//			if(task.getLineId()==null) {
//				throw new BusinessException("line.is.null","线路为空");
//			}
//		}
//		/*** ???用管理员查询自己领取过的任务？？？我感觉这个写的逻辑不对 **/
//		List<Task> list = selectTaskUserList(task.getUserId(), "2");
//		if(list !=null && list.size() >0) {
//			for(Task t:list) {
//				//如果是紧急任务
//				if(t.getTaskLevel() !=null && t.getTaskLevel().intValue()==2) {
//					throw new BusinessException("taskLevel.is.two");
//				}
//			}
//		}
//		/** 创建要完善的实体*/
//		//主键
//		String id = UUIDUtil.getUUID();
//		task.setId(id);
//		//创建时间
//		task.setCreatTime(new Date());
//		//默认未删除
//		task.setIsDelete((short)0);
//
//
//		//是否指定所有人
//		String isSpecify = String.valueOf(task.getIsSpecify());
//
//		if ("1".equals(isSpecify)){
//			Example example = new Example(TaskReceivingRecords.class);
//			example.and().andEqualTo("userId",insertTaskVo.getBusinessId().split(",")[0]).andEqualTo("tastStatus",2);
//			List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectByExample(example);
//			for (TaskReceivingRecords receivingRecord : taskReceivingRecords) {
//				String taskId = receivingRecord.getTaskId();
//				Task task1 = this.mapper.selectByPrimaryKey(taskId);
//				if ( task1.getTaskLevel() == 2 ){
////					throw new BusinessException("user.is.Busy");
//				} else if (receivingRecord.getTastStatus() == 2 && task1.getTaskLevel() == 1 && task.getTaskLevel() == 2){
//					tempTaskMap.put(id, receivingRecord.getId());
//					receivingRecord.setTastStatus((short)4);
//					taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
//				}
//			}
//			System.err.println("2.指定人员--");
//			System.err.println("2.task.userId="+task.getUserId());
//		}else if ("2".equals(isSpecify)){
//			//部门
//			List<Users> users = this.usersService.selectUsersListOnTeamById(insertTaskVo.getBusinessId());
//			for (Users u : users) {
//				Example example = new Example(TaskReceivingRecords.class);
//				example.and().andEqualTo("userId",u.getId()).andEqualTo("tastStatus",2);
//				List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectByExample(example);
//				for (TaskReceivingRecords receivingRecord : taskReceivingRecords) {
//					String taskId = receivingRecord.getTaskId();
//					Task task1 = this.mapper.selectByPrimaryKey(taskId);
//					if (task1.getTaskLevel() == 2 ){
////						throw new BusinessException("user.is.Busy");
//					}else if (receivingRecord.getTastStatus() == 2 && task1.getTaskLevel() == 1 && task.getTaskLevel() == 2){
//						tempTaskMap.put(id, receivingRecord.getId());
//						receivingRecord.setTastStatus((short)4);
//						taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
//					}
//				}
//			}
//			System.err.println("3.指定部门--");
//			System.err.println("3.task.userId="+task.getUserId());
//		}else if ("3".equals(isSpecify)){
//			//工种
//			Example exp = new Example(Users.class);
//			exp.and().andEqualTo("workId",insertTaskVo.getBusinessId());
//			List<Users> users = this.usersService.selectByExample(exp);
//			for (Users u : users) {
//				Example example = new Example(TaskReceivingRecords.class);
//				example.and().andEqualTo("userId",u.getId()).andEqualTo("tastStatus",2);
//				List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectByExample(example);
//				for (TaskReceivingRecords receivingRecord : taskReceivingRecords) {
//					String taskId = receivingRecord.getTaskId();
//					Task task1 = this.mapper.selectByPrimaryKey(taskId);
//					if (task1.getTaskLevel() == 2){
////						throw new BusinessException("user.is.Busy");
//					}else if (receivingRecord.getTastStatus() == 2 && task1.getTaskLevel() == 1 && task.getTaskLevel() == 2){
//						tempTaskMap.put(id, receivingRecord.getId());
//						receivingRecord.setTastStatus((short)4);
//						taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
//					}
//				}
//			}
//			System.err.println("4.指定工种--");
//			System.err.println("4.task.userId="+task.getUserId());
//		}
//
//		if (task.getTaskType() == 2){
//			TaskLine taskLine = new TaskLine();
//			List<TaskDetails> detailsList = new ArrayList<>();
//			TaskDetails details = new TaskDetails();
//			details.setId(UUIDUtil.getUUID());
//			details.setIsDelete((short)0);
//			details.setTaskId(task.getId());
//			details.setTaskFlow((short)1);
//			details.setTaskOperation((short)1);
//			details.setLat(task.getTaskLat());
//			details.setLog(task.getTaskLog());
//			detailsList.add(details);
//			System.out.println(detailsList.toString());
//			taskLine.setTaskDetailsList(detailsList);
//			String s = taskLineService.insertOrUpdateTaskLine(taskLine);
//			task.setLineId(s);
//		}
//
//		//新增任务实体
//		int k = this.mapper.insertSelective(task);
//		boolean flag = true;
//		if(k >0) {
//			//添加任务指定的领取人
//			if(task.getIsSpecify() !=null) {
//				this.taskBusinessService.insertTaskBusiness(String.valueOf(task.getIsSpecify()), insertTaskVo.getBusinessId(), id);
//			}
//		}
//
//		System.err.println("指定添加领取人之后--");
//		System.err.println("task.userId="+task.getUserId());
//		HashMap<String, String> map = new HashMap<>();
//		map.put("fromUserId",task.getUserId());
//		if(VariableConstants.STRING_CONSTANT_1.equals(isSpecify)){
//			System.out.println("1111111::::::"+insertTaskVo.getBusinessId());
//			String[] split = insertTaskVo.getBusinessId().split(",");
//			StringBuffer stringBuffer = new StringBuffer();
//			for (String s : split) {
//				stringBuffer.append(s + "&");
//			}
//			//仅对指定员工发生任务信息
//			map.put("toUserId",stringBuffer.toString());
//		} else if (VariableConstants.STRING_CONSTANT_2.equals(isSpecify)){
//			System.out.println("22222222");
//			//仅对该部门的人发送任务信息
//			String[] Bid = insertTaskVo.getBusinessId().split(",");
//			List<Users> users = this.usersService.selectselectUsersListBybusinessIds("1", Bid);
//			StringBuffer ids = new StringBuffer();
//			for (Users u : users) {
//				ids.append(u.getId() + "&");
//			}
//			map.put("toUserId",ids.toString());
//			map.put("objectName","RC:TxtMsg");
//			JSONObject jsonObject = new JSONObject();
//			jsonObject.put("content", "您有新的任务！");
//			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
//			map.put("content",jsonObject.toJSONString());
//			map.put("pushContent","您有新的任务");
//			try {
//				String s = RongUtils.groupManagement(map, "7");
//				System.out.println(s);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			flag = false;
//
//		} else if (VariableConstants.STRING_CONSTANT_3.equals(isSpecify)){
//			System.out.println("33333333");
//			//仅对该工种发送任务信息
//			String[] Bid = insertTaskVo.getBusinessId().split(",");
//			List<Users> users = this.usersService.selectselectUsersListBybusinessIds("2", Bid);
//			StringBuffer ids = new StringBuffer();
//			for (Users u : users) {
//				ids.append(u.getId() + "&");
//			}
//			map.put("toUserId",ids.toString());
//			map.put("objectName","RC:TxtMsg");
//			JSONObject jsonObject = new JSONObject();
//			jsonObject.put("content", "您有新的任务！");
//			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
//			map.put("content",jsonObject.toJSONString());
//			map.put("pushContent","您有新的任务");
//			try {
//				String s = RongUtils.groupManagement(map, "7");
//				System.out.println(s);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			flag = false;
//		}
//		if(flag){
//			map.put("objectName","RC:TxtMsg");
//			JSONObject jsonObject = new JSONObject();
//			jsonObject.put("content", "您有新的任务！");
//			jsonObject.put("extra", "任务名称:" + insertTaskVo.getTask().getTaskName());
//			map.put("content",jsonObject.toJSONString());
//			map.put("pushContent","您有新的任务");
//			try {
//				String s = RongUtils.groupManagement(map, "7");
//				System.out.println(s);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//		System.err.println("5.程序执行到最后--");
//		System.err.println("5.task.userId="+task.getUserId());
//	}
	
	/******
	 * 
	     * @方法名：selectTaskUserList
	     * @描述： 查询用户已经领取的任务
	     * @作者： lijing
	     * @日期： 2019年7月23日
	     * @param  "staus" :【字典tastStatus】
	 */
	public List<Task> selectTaskUserList(String userId,String status){
		
		if(userId == null) {
			UserInfo user = PartyUtil.getCurrentUserInfo();
			if(user == null) {
				throw new BusinessException("not.login");
			}
			userId = user.getId();
		}
		List<Task> list = this.mapper.selectTaskUserList(userId, status,null,null,null,null);
		return list;
	}
	
	
	/****
	 * 
	     * @方法名：startTask
	     * @描述： 开始任务
	     * @作者： lijing
	     * @日期： 2019年7月15日
	 */
	@Transactional(rollbackFor = Exception.class)
	public void startTask(String id) {
		Optional.ofNullable(id).orElseThrow(() -> new BusinessException("id.is.null"));

		//获取用户登录信息
		UserInfo activeUser = PartyUtil.getCurrentUserInfo();
		Optional.ofNullable(activeUser).orElseThrow(() -> new BusinessException("not.login"));

		//获取登录用户id
		String userId = activeUser.getId();
		System.err.println("userId="+userId);
		List<Task> list = selectTaskUserList(userId, "2");

		//查询任务
		List<Task> tasks = this.mapper.selectTaskByUserId(id, userId);
		Task task = tasks.get(0);

		//如果有紧急任务则不能直接正常任务
		if (taskReceivingRecordsService.selectTaskUrgentByUserId(userId) && task.getTaskLevel() != 2){
			throw new BusinessException("task.urgent.isexist");
		}

		if(list !=null && list.size() >0) {
			for (Task t : list) {
				/*if (t.getTaskLevel() == 2){
					throw new BusinessException("task.is.repeat");
				}else{
					List<TaskReceivingRecords> records = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(t.getId(),userId, null);
					for (TaskReceivingRecords record : records) {
						record.setTastStatus((short)4);
						this.taskReceivingRecordsService.updateTaskReceivingRecords(record);
					}
				}*/
				List<TaskReceivingRecords> records = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(t.getId(),userId, null);
				for (TaskReceivingRecords record : records) {
					record.setTastStatus((short)4);
					this.taskReceivingRecordsService.updateTaskReceivingRecords(record);
				}
			}
			list = null;

		}
		if(task == null) {
			throw new BusinessException("task.is.null");
		}
		if(task.getTaskStatus() != null && VariableConstants.STRING_CONSTANT_2.equals(task.getTaskStatus())) {
			throw new BusinessException("task.is.start");
		}
		List<TaskReceivingRecords> records = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskId(task.getId(), null, null);
		for (TaskReceivingRecords record : records) {
			record.setTaskStartTime(new Date());
			record.setTastStatus((short) 2);
			this.taskReceivingRecordsService.updateTaskReceivingRecords(record);
		}

	}
	
	/****
	 * 
	     * @方法名：applicationRevocationTask
	     * @描述： 申请撤销
	     * @作者： lijing
	     * @日期： 2019年7月15日
	 */
	@Transactional(rollbackFor=BusinessException.class)
	public int applicationRevocationTask(String id,String exceptionContext,String reasonsRevocation,String nickName) {

		Optional.ofNullable(id).orElseThrow(() -> new BusinessException("id.is.null"));
		Optional.ofNullable(exceptionContext).orElseThrow(() -> new BusinessException("exceptionContext.is.null"));
		Optional.ofNullable(reasonsRevocation).orElseThrow(() -> new BusinessException("reasonsRevocation.is.null"));

		/*Example e = new Example(TaskExceptionDescription.class);
		e.and().andEqualTo("taskId",id);
		List<TaskExceptionDescription> taskExceptionDescriptions = taskExceptionDescriptionService.selectByExample(e);
		if (taskExceptionDescriptions.size() > 0){
			throw new BusinessException("repeated.revocation");
		}*/
		UserInfo currentUser = PartyUtil.getCurrentUserInfo();
		Optional.ofNullable(currentUser).orElseThrow(() -> new BusinessException("not.login"));

		//景区id
		String scenicId = currentUser.getScenicId();
		//申请人id
		String proposerId = currentUser.getId();
		System.err.println("proposerId="+proposerId);

		//查询任务
		List<Task> tasks = this.mapper.selectTaskByUserId(id, proposerId);
		Task task = tasks.get(0);
		Optional.ofNullable(task).orElseThrow(() -> new BusinessException("task.is.null"));

		//处理人id(任务发布人id)
		String handlerId = task.getUserId();
		System.err.println("handlerId="+handlerId);
		Users manager = this.usersService.selectUsersById(handlerId);
		BackUser backUser = backUserMapper.selectBackUserById(handlerId);

		if(manager==null && backUser==null){
			throw new BusinessException("handlerId.is.null");
		}

		//任务状态
		Short taskStatus = (short)4;

		//任务异常说明的处理状态
		Short handlerStatus = (short)0;

		//发起撤销任务申请的用户类型
		String userType = currentUser.getUserType();
		//如果是管理端用户自己发布的任务，直接一次性把任务状态改为已撤销
		if(userType.equals(VariableConstants.STRING_CONSTANT_2) && handlerId.equals(proposerId)){
			taskStatus = (short)3;
			handlerStatus = (short)1;
		}

		//返回结果
		int result = 0;

		//任务领取记录
		TaskReceivingRecords tr = new TaskReceivingRecords();
		tr.setTaskId(task.getId());
		tr.setTastStatus(taskStatus);
		this.taskReceivingRecordsService.updateTaskReceivingRecords(tr);

		//任务异常说明
		Example example = new Example(TaskExceptionDescription.class);
		example.and().andEqualTo("taskId",task.getId()).andEqualTo("userId",proposerId);
		List<TaskExceptionDescription> list = this.taskExceptionDescriptionService.selectByExample(example);
		if (list.size() > 0){
			for (TaskExceptionDescription description : list) {
				description.setHandlerStatus(handlerStatus);
				description.setTastStatus(taskStatus);
				description.setExceptionContext(exceptionContext);
				description.setReasonsRevocation(Short.valueOf(reasonsRevocation));
				result = this.taskExceptionDescriptionService.insertOrUpdateTaskExceptionDescription(description);
			}
		}else {
			//新增任务异常列表
			TaskExceptionDescription td = new TaskExceptionDescription()
					.setExceptionContext(exceptionContext)
					.setHandlerStatus(handlerStatus)
					.setTaskId(task.getId())
					.setTastStatus(taskStatus)
					.setUserId(currentUser.getId())
					.setReasonsRevocation(Short.valueOf(reasonsRevocation))
					.setScenicId(scenicId);
			result = this.taskExceptionDescriptionService.insertOrUpdateTaskExceptionDescription(td);
		}

		if(userType.equals(VariableConstants.STRING_CONSTANT_2) && handlerId.equals(proposerId)){
			/** 用户类型为管理端 且 任务就是自己发的，就不用发融云消息通知*/
			return result;
		}else if(backUser!=null){
			/** 如果任务发布人是后台管理员，也不发融云消息通知*/
			return result;
		}



		/************************ 融云消息通知 ************************/
		HashMap<String, String> map = new HashMap<>();
		//消息发起人
		map.put("fromUserId",proposerId);
		//消息接收人
		map.put("toUserId",handlerId);
		JSONObject applicationJsonObject = new JSONObject();
		//标题
		String approvalTitle = nickName+"发出的撤销任务申请";
		applicationJsonObject.put("approvalTitle",approvalTitle);
		//任务id
		applicationJsonObject.put("taskId",id);
		//撤销理由
		applicationJsonObject.put("reasonsRevocation", DictUtil.getDisplay("reasonsRevocation",reasonsRevocation));
		//任务异常说明
		applicationJsonObject.put("exceptionContext",exceptionContext);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("content", approvalTitle);
		jsonObject.put("extra", applicationJsonObject.toJSONString());
		map.put("objectName","RC:TxtMsg");
		map.put("content",jsonObject.toJSONString());
		map.put("pushContent","撤销任务请求");

		try {
			String s = RongUtils.groupManagement(map, "7");
			System.out.println(s);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
	
	/****
	 * 
	     * @方法名：automaticCollectionTask
	     * @描述： 每日自动领取任务
	     * @作者： lijing
	     * @日期： 2019年8月21日
	 */
	public void automaticCollectionTask() {
		
		SelectTaskListVo selectTaskListVo = new SelectTaskListVo();
		selectTaskListVo.setTaskCategories("1");
		selectTaskListVo.setTaskType("3");
		selectTaskListVo.setTaskEndType("1");
		//查询巡更任务
		List<Task> list = this.mapper.selectTaskListOnBack(selectTaskListVo);
		if(list !=null && list.size() >0) {
			list.stream().forEach((t) ->{
				List<String> userList = this.taskBusinessService.getTaskBusinessList(t.getId());
				if(userList!=null && userList.size() >0) {
					//添加用户领取记录
					this.taskReceivingRecordsService.insertTaskReceivingRecords(userList,t.getId());
				}
			});
		}
		selectTaskListVo = null;
	}

	/**
	 * @方法名：deleteTaskTimingByIdOnBack
	 * @描述： 批量删除定时任务(逻辑删除)
	 * @作者： Kuang.JiaZhuo
	 * @日期： Created in 2019/10/25 18:39
	 */
	/*@Transactional(rollbackFor = Exception.class)
	public void deleteTimingTaskParameterByIdOnBack(String ids) {
		Optional.ofNullable(ids).orElseThrow(() -> new BusinessException("id.is.null"));
		String[] idArrys = ids.split(",");
		List<String> list = Arrays.asList(idArrys);
		List<TimingTaskParameter> collect = list.stream()
				.map((iid) -> {
					TimingTaskParameter timingTaskParameter = new TimingTaskParameter().setId(iid).setIsDelete(VariableConstants.STRING_CONSTANT_1);
					this.timingTaskParameterService.updateSelectiveById(timingTaskParameter);
					return timingTaskParameter;
				}).collect(Collectors.toList());
	}*/

	/**
	 * @方法名：deleteTimingTaskParameterByIdOnBack
	 * @描述： 批量删除定时任务参数(物理删除)
	 * @作者： kjz
	 * @日期： Created in 2020/4/22 16:18
	 */
	@Transactional(rollbackFor = Exception.class)
	public int deleteTimingTaskParameterByIdOnBack(String ids) {
		Optional.ofNullable(ids).orElseThrow(() -> new BusinessException("id.is.null"));
		String[] idArrys = ids.split(",");
		List<String> list = Arrays.asList(idArrys);
		int result = 0;
		//定时任务领取参数
		this.timingTaskDesignatedReceiverMapper.deleteTaskDesignatedReceiverByTaskIds(list);
		//定时任务保存的发布时间
		this.taskTimingMapper.deleteTaskTimingByTaskIds(list);
		//定时任务具体发布时间记录
		this.taskSpecificReleaseTimeMapper.deleteTaskSpecificReleaseTimeByTaskIds(list);
		result = this.timingTaskParameterMapper.deleteTaskParameterByIds(list);
		return result;
	}

	/**
	 * @方法名：insertTimedTaskVo
	 * @描述： 新增定时任务
	 * @作者： 王海洋
	 * @日期： Created in 2019/10/26 13:44
	 */
	@Transactional(rollbackFor = Exception.class)
	public void insertTimedTask(InsertTimedTaskVo insertTimedTaskVo) {
		System.err.println("-----定时任务参数-----");
		System.err.println(JSON.toJSON(insertTimedTaskVo));
		//获取当前登录用户信息
		UserInfo currentUser = PartyUtil.getCurrentUserInfo();
		if(currentUser == null) {
			throw new BusinessException("not.login");
		}
		/** 景区id */
		String scenicId = currentUser.getScenicId();
        System.err.println("currentUser="+currentUser);
		//任务实体
		Task task = insertTimedTaskVo.getTask();
		//任务名称为空(这是copy的原来的写法，不太清楚为啥要这么操作)
		if (task.getTaskName() == null || "".equals(task.getTaskName())){
			task.setTaskName(task.getTaskTypeDisplay()+new Date());
		}

		System.err.println("task="+task);
		Optional.ofNullable(insertTimedTaskVo).orElseThrow(() -> new BusinessException("task.is.null","任务为空，发布失败"));
		Optional.ofNullable(insertTimedTaskVo.getBusinessId()).orElseThrow(() -> new BusinessException("businessId.is.null"));
		Optional.ofNullable(task.getTaskType()).orElseThrow(() -> new BusinessException("taskType.is.null"));
		Optional.ofNullable(task.getTaskLevel()).orElseThrow(() -> new BusinessException("taskLevel.is.null"));
		Optional.ofNullable(task.getTaskCategories()).orElseThrow(() -> new BusinessException("taskCategories.is.null"));
		Optional.ofNullable(task.getIsSpecify()).orElseThrow(() -> new BusinessException("isSpecify.is.null"));


		/** 如果是巡更任务，线路id不能为空 */
		if(task.getTaskType() !=null && task.getTaskType().intValue()==3) {
			Optional.ofNullable(task.getLineId()).orElseThrow(() -> new BusinessException("line.is.null"));
		}else{
			//非巡更任务必传经纬度
			Optional.ofNullable(task.getTaskLat()).orElseThrow(() -> new BusinessException("taskLat.is.null"));
			Optional.ofNullable(task.getTaskLog()).orElseThrow(() -> new BusinessException("taskLog.is.null"));
		}

		/*** 原来的代码:???查询当前登录用户(也就是后台管理员)已经领取的正在进行的任务，后台管理员有个毛的任务？？？？？ **/
		/*List<Task> list = selectTaskUserList(currentUser.getId(), "2");
		if(list !=null && list.size() >0) {
			for(Task t:list) {
				//如果是紧急任务
				if(t.getTaskLevel() !=null && t.getTaskLevel().intValue()==2) {
					throw new BusinessException("taskLevel.is.two");
				}
			}
		}*/

		/***  以前的逻辑代码搬运过来改的，只留下了判断指定领取人是否正在进行紧急任务的抛出异常的部分，其他新增操作取消了没有执行*/
		//现在这一块的原来的业务判断和定时任务有冲突，所以注释了部分

		/*if(isSpecify.equals(VariableConstants.STRING_CONSTANT_1)){
			*//***  按人员指定 **//*
			//查询指定的人员中正在进行的任务领取记录
			List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectTaskReceivingRecordsByTaskStatus(insertTimedTaskVo.getBusinessId(),2);
			if(!taskReceivingRecords.isEmpty()){
				for (TaskReceivingRecords receivingRecord : taskReceivingRecords){
					//查询正在进行中的任务的级别如果是【紧急】,就抛出异常
					String taskId = receivingRecord.getTaskId();
					Task originalTask = this.mapper.selectByPrimaryKey(taskId);
					if ( originalTask.getTaskLevel() == 2 ){
						throw new BusinessException("user.is.Busy");
					}*//*else if (receivingRecord.getTastStatus() == 2 && originalTask.getTaskLevel() == 1 && task.getTaskLevel() == 2){
						//如果该员工原来有正在进行中的【任务级别为正常】的任务,那么就要把原来正在进行中的任务状态改为【暂停】
						receivingRecord.setTastStatus((short)4);
						taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
					}*//*
				}
			}
		}*/
		/*if(isSpecify.equals(VariableConstants.STRING_CONSTANT_2)){
			*//***  按部门指定 **//*
			//查询出当前指定部门的所有员工
			//现在这一块的原来的业务判断和定时任务有冲突，所以注释了部分
			List<Users> users = this.usersService.selectUsersListOnTeamById(insertTimedTaskVo.getBusinessId());
			if(!users.isEmpty()){
				for (Users u : users) {
					//查询出有正在进行中任务的员工任务领取记录
					Example example = new Example(TaskReceivingRecords.class);
					example.and().andEqualTo("userId", u.getId()).andEqualTo("tastStatus", 2);
					List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectByExample(example);
					if(!taskReceivingRecords.isEmpty()){
						for (TaskReceivingRecords receivingRecord : taskReceivingRecords) {
							//查询正在进行中的任务的级别如果是【紧急】,就抛出异常
							String taskId = receivingRecord.getTaskId();
							Task originalTask = this.mapper.selectByPrimaryKey(taskId);
							if (originalTask.getTaskLevel() == 2) {
								throw new BusinessException("user.is.Busy");
							} *//*else if (receivingRecord.getTastStatus() == 2 && originalTask.getTaskLevel() == 1 && task.getTaskLevel() == 2) {
								//如果该员工原来有正在进行中的【任务级别为正常】的任务,那么就要把原来正在进行中的任务状态改为【暂停】
								receivingRecord.setTastStatus((short) 4);
								taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
							}*//*

						}
					}

				}
			}
		}*/
		/*if(isSpecify.equals(VariableConstants.STRING_CONSTANT_3)){
			*//***  按工种指定 **//*
			//查询指定的工种中人员正在进行的任务领取记录
			//现在这一块的原来的业务判断和定时任务有冲突，所以注释了部分
			List<TaskReceivingRecords> taskReceivingRecords = this.taskReceivingRecordsService.selectTaskReceivingRecordsByWorkId(insertTimedTaskVo.getBusinessId(),2);
			for (TaskReceivingRecords receivingRecord : taskReceivingRecords) {
				//查询正在进行中的任务的级别如果是【紧急】,就抛出异常
				String taskId = receivingRecord.getTaskId();
				Task originalTask = this.mapper.selectByPrimaryKey(taskId);
				if (originalTask.getTaskLevel() == 2) {
					throw new BusinessException("user.is.Busy");
				}*//*else if (receivingRecord.getTastStatus() == 2 && originalTask.getTaskLevel() == 1 && task.getTaskLevel() == 2){
					//如果该员工原来有正在进行中的【任务级别为正常】的任务,那么就要把原来正在进行中的任务状态改为【暂停】
					receivingRecord.setTastStatus((short)4);
					taskReceivingRecordsService.updateTaskReceivingRecords(receivingRecord);
				}*//*
			}
		}*/

        //获取登录用户的id信息干什么？
		if(currentUser.getId()==null || "".equals(currentUser.getId())){
		    throw new BusinessException("userId.is.null");
        }

		/** 如果发布的是临时任务 */
		//任务类别
		Short taskCategories = insertTimedTaskVo.getTask().getTaskCategories();
		//临时发布类型
		Short publishType = insertTimedTaskVo.getTask().getPublishType();
		//临时任务发布时间
		String publishTime = insertTimedTaskVo.getTask().getPublishTime();
		if(taskCategories.intValue()==2 && !StringUtil.isEmpty(publishType)){
			if(!StringUtil.isEmpty(publishType) && publishType.intValue()==2){
				insertTimedTaskVo.setPublishTime(publishTime.substring(0,16));
				insertTimedTaskVo.setPublishType(publishType.toString());
				publishTimeTask(insertTimedTaskVo);
			}else{
				InsertTaskVo insertTaskVo = new InsertTaskVo();
				BeanUtils.copyProperties(insertTimedTaskVo,insertTaskVo);
				insertTask(insertTaskVo);
			}
		}else{
			publishTimeTask(insertTimedTaskVo);
		}
	}

	/**
	 * @方法名：publishTimeTask
	 * @描述： 发布巡更常规任务
	 * @作者： 王海洋
	 * @日期： Created in 2019/10/26 13:44
	 */
	@Transactional(rollbackFor = Exception.class)
	public void publishTimeTask(InsertTimedTaskVo insertTimedTaskVo){
		Task task = insertTimedTaskVo.getTask();
		UserInfo user = PartyUtil.getCurrentUserInfo();
		if(user == null) {
			throw new BusinessException("not.login");
		}

		/** 景区id */
		String scenicId = user.getScenicId();

		String isSpecify = String.valueOf(task.getIsSpecify());
		/** 新增定时任务的参数*/
		//定时任务参数id
		String timingTaskParameterId = UUIDUtil.getUUID();
		TimingTaskParameter timingTaskParameter = new TimingTaskParameter()
				//id
				.setId(timingTaskParameterId)
				//创建时间
				.setCreateTime(new Date())
				//默认未删除
				.setIsDelete(VariableConstants.STRING_CONSTANT_0)
				//发布人id
				.setUserId(user.getId())
				//业务id
				.setBusinessId(insertTimedTaskVo.getBusinessId())
				//任务类型
				.setTaskType(task.getTaskType())
				//任务级别
				.setTaskLevel(task.getTaskLevel())
				//是否指定所有人员
				.setIsSpecify(task.getIsSpecify())
				//任务类别
				.setTaskCategories(task.getTaskCategories())
				//任务说明
				.setTaskStatement(task.getTaskStatement())
				//任务名字
				.setTaskName(task.getTaskName())
				//纬度
				.setTaskLat(task.getTaskLat())
				//经度
				.setTaskLog(task.getTaskLog())
				//线路id
				.setLineId(task.getLineId())
				//景区id
				.setScenicId(scenicId)
				//执行任务的地名
				.setLocation(insertTimedTaskVo.getLocation());

		if(!StringUtil.isEmpty(insertTimedTaskVo.getPublishType()) && insertTimedTaskVo.getPublishType().equals("2")){
			timingTaskParameter.setPublishType(Short.valueOf(insertTimedTaskVo.getPublishType()));
		}

		//启用状态默认启用
		String enabled = insertTimedTaskVo.getEnabled();
		if(enabled==null){
			timingTaskParameter.setEnabled(VariableConstants.STRING_CONSTANT_1);
		}else{
			timingTaskParameter.setEnabled(enabled);
		}
		this.timingTaskParameterMapper.insert(timingTaskParameter);

		System.out.println(timingTaskParameter.getUserId());

		/** 新增定时任务指定领取人*/
		TimingTaskDesignatedReceiver timingTaskDesignatedReceiver = new TimingTaskDesignatedReceiver();
		timingTaskDesignatedReceiver.setTimedTaskId(timingTaskParameterId);
		if(isSpecify.equals(VariableConstants.STRING_CONSTANT_1)){
			//按指定人员
			List<String> userList = Arrays.asList(insertTimedTaskVo.getBusinessId().split(","));
			for(String userId:userList){
				timingTaskDesignatedReceiver.setUserId(userId).setScenicId(scenicId);
				this.timingTaskDesignatedReceiverService.insertTimingTaskDesignatedReceiver(timingTaskDesignatedReceiver);
			}
		}
		if(isSpecify.equals(VariableConstants.STRING_CONSTANT_2)){
			//按指定部门
			List<Users> users = this.usersService.selectUsersListOnTeamById(insertTimedTaskVo.getBusinessId());
			for(Users user1:users){
				timingTaskDesignatedReceiver.setUserId(user1.getId()).setScenicId(scenicId);;
				this.timingTaskDesignatedReceiverService.insertTimingTaskDesignatedReceiver(timingTaskDesignatedReceiver);
			}

		}
		if(isSpecify.equals(VariableConstants.STRING_CONSTANT_2)){
			//按指定工种
			List<Users> users = this.usersService.selectselectUsersListBybusinessIds("2",insertTimedTaskVo.getBusinessId().split(","));
			for(Users user1:users){
				timingTaskDesignatedReceiver.setUserId(user1.getId()).setScenicId(scenicId);;
				this.timingTaskDesignatedReceiverService.insertTimingTaskDesignatedReceiver(timingTaskDesignatedReceiver);
			}

		}
		//是否临时
		String publishType = insertTimedTaskVo.getPublishType();
		//如果是临时任务的定时发布
		if(publishType!=null && publishType.equals(VariableConstants.STRING_CONSTANT_2)){
			//自己组装传入星期X
			insertTimedTaskVo.setPubWeeks(DateUtil.dateStr2Week(insertTimedTaskVo.getPublishTime(),"yyyy-MM-dd HH:mm"));
			//自己传入发布时间
			insertTimedTaskVo.setPubTime(insertTimedTaskVo.getPublishTime());
		}

		System.err.println("insertTimedTaskVo="+insertTimedTaskVo);
		/** 新增定时任务的指定时间*/
		Optional.ofNullable(insertTimedTaskVo.getPubWeeks()).orElseThrow(() -> new BusinessException("pubWeek.is.null"));
		Optional.ofNullable(insertTimedTaskVo.getPubTime()).orElseThrow(() -> new BusinessException("pubTime.is.null"));
		TaskTiming taskTiming = new TaskTiming()
				.setTaskId(timingTaskParameterId)
				.setPubWeeks(insertTimedTaskVo.getPubWeeks())
				.setPubTime(insertTimedTaskVo.getPubTime())
				//景区id
				.setScenicId(scenicId);
		if(!StringUtil.isEmpty(insertTimedTaskVo.getPublishType()) && insertTimedTaskVo.getPublishType().equals("2")){
			taskTiming.setPubTime(insertTimedTaskVo.getPublishTime());
			String publishTime = insertTimedTaskVo.getPublishTime();
			System.err.println("publishTime="+publishTime);
			String weekDay = TaskUtil.getForWeeks(publishTime);
			taskTiming.setPubWeek(weekDay);
			this.taskTimingService.insertOrUpdateTaskTimingMobile(taskTiming);
		}else{
			this.taskTimingService.insertOrUpdateTaskTiming(taskTiming);
		}
	}

	/**
	 * @方法名：selectTemporaryTaskManageByCondition
	 * @描述： 后台&管理端-查询临时任务管理列表(已废弃)
	 * @作者： kuang.jiazhuo
	 * @日期： Created in 2019/12/4 16:21
	 */
	public PageInfo<TemporaryTaskManageView> selectTemporaryTaskManageByCondition(TemporaryTaskManageVo temporaryTaskManageVo) {
		PageHelper.startPage(temporaryTaskManageVo.getNum(),temporaryTaskManageVo.getSize());
		List<TemporaryTaskManageView> list =this.mapper.selectTemporaryTaskManageByCondition(temporaryTaskManageVo);
		PageInfo<TemporaryTaskManageView> p = new PageInfo<>(list);
		return p;
	}

	/**
	 * @方法名：revokeTaskById
	 * @描述： 移动端-根据id撤销任务
	 * @作者： kjz
	 * @日期： Created in 2020/4/7 15:38
	 */
	@Transactional(rollbackFor = Exception.class)
	public int revokeTaskById(String taskId) {

		Optional.ofNullable(taskId).orElseThrow(() -> new BusinessException("id.is.null"));
		int result = this.taskReceivingRecordsService.updateTastStatusByTaskId(taskId,(short)3);

		return result;
	}

	/**
	 * @方法名：updateTaskByUserIsUsing
	 * @描述： 根据用户的是否启用状态更新是否禁用用户
	 * @作者： kjz
	 * @日期： Created in 2020/4/8 14:52
	 */
	@Transactional(rollbackFor = Exception.class)
	public int updateTaskByUserIsUsing(Users users) {
		int result = 0;
		Short isUsing = users.getIsUsing();
		String userId = users.getId();
		String userType = users.getUserType();
		String teamId = users.getUserTeamList().get(0).getTeamId();
		String workId = users.getWorkId();
		if(isUsing==0){
			/** 如果禁用用户，用户存在的任务关联数据全部逻辑删除*/
			//逻辑删除员工id关联的任务计划
			this.timingTaskParameterMapper.disabledTimingTaskByUserId(userId);
			//员工端要查工种关联
			if(userType.equals("1")){

			}
		}else{
			/** 如果启用用户，用户存在的任务关联数据全部恢复*/
		}
		return result;
	}
}
